package test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.Scanner;

public class Add {
	public static Configuration configuration;
	public static Connection connection;
	public static Admin admin;

	public static void init() {
		configuration = HBaseConfiguration.create();
		configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase");
		try {
			connection = ConnectionFactory.createConnection(configuration);
			admin = connection.getAdmin();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void close() {
		try {
			if (admin != null)
				admin.close();
			if (null != connection)
				connection.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void insertRow(String tableName, String row, String column, String c, String val) throws IOException {
		init();
		Table table = connection.getTable(TableName.valueOf(tableName));
		Put put = new Put(row.getBytes());
		put.addColumn(column.getBytes(), c.getBytes(), val.getBytes());
		table.put(put);
		System.out.println("成功添加！");
		table.close();
		close();
	}

	public static void deleteRow(String tableName, String row, String column, String c) throws IOException {
		init();
		Table table = connection.getTable(TableName.valueOf(tableName));
		System.out.println("1、删除列族;2、删除列限定符");
		Scanner sc = new Scanner(System.in);
		int no = sc.nextInt();
		Delete delete = new Delete(row.getBytes());
		if (no == 1) {
			delete.addFamily(Bytes.toBytes(column));
			System.out.println("成功删除" + column + "这个列族");
		} else if (no == 2) {
			delete.addColumn(Bytes.toBytes(column), Bytes.toBytes(c));
			System.out.println("成功删除" + c + "这个列限定符");
		}
		table.delete(delete);
		table.close();
		close();
	}

	public static void addOrDelete(String tableName, String row, String column, String c, String val) throws IOException {
		System.out.println("1、添加列;2、删除列");
		Scanner sc=new Scanner(System.in);
		int no = sc.nextInt();
		if (no == 1) {
			insertRow(tableName, row, column, c, val);
		} else if (no == 2) {
			deleteRow(tableName, row, column, c);
		}
	}
	public static void main(String[] args) throws IOException{
		Add add=new Add();
		add.addOrDelete("student", "0", "1", "2", "1");
		add.addOrDelete("student", "0", "1", "2", "1");
	}
}
